package com.yisu.expressway.service_district;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.R;
import com.yisu.expressway.activity.BaseActivity;
import com.yisu.expressway.application.ExApplication;
import com.yisu.expressway.location.LocationInfo;
import com.yisu.expressway.location.LocationListener;
import com.yisu.expressway.location.LocationService;
import com.yisu.expressway.model.ServiceDistrictItem;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.ui.recyclerview.DividerListItemDecoration;
import com.yisu.expressway.utils.StringUtil;
import com.yisu.expressway.utils.ToastUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SearchDistrictAreaActivity extends BaseActivity implements TextWatcher {

    @Bind(R.id.edt_search)
    protected EditText mEdt_Search;
    @Bind(R.id.search_clear_bt)
    protected ImageView mIv_clear;
    @Bind(R.id.rv_service_list)
    protected RecyclerView mRv_list;

    private LocationInfo locInfo;
    ServiceDistrictAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_district_area);
        initView();
    }

    private void initView(){
        getCurrentLocation();
        mEdt_Search.addTextChangedListener(this);
        mRv_list.addItemDecoration(new DividerListItemDecoration(this, DividerListItemDecoration.VERTICAL_LIST));
        mRv_list.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ServiceDistrictAdapter();
        mRv_list.setAdapter(mAdapter);
    }

    private void getCurrentLocation(){
        LocationService.getInstance().start(new LocationListener() {
            @Override
            public void onSuccess(LocationInfo info) {
                locInfo = info;
            }

            @Override
            public void onFailure(int errorCode, String errorMessage) {
                ToastUtil.displayShortToastMsg(SearchDistrictAreaActivity.this,errorMessage);
            }
        });
    }

    @OnClick({R.id.iv_back,R.id.iv_search_action,R.id.search_clear_bt})
    public void onClickAction(ImageView view){
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_search_action:
                searchDistrict();
                break;
            case R.id.search_clear_bt:
                mEdt_Search.setText("");
                break;
            default:
                break;
        }
    }

    private void searchDistrict(){
        String keyword = mEdt_Search.getText().toString();
        if(StringUtil.isNullOrEmpty(keyword)){
            mAdapter.clearData();
            return;
        }
        Map<String, Object> params = new HashMap();
        params.put("longitude", locInfo.getLongitude());
        params.put("latitude", locInfo.getLatitude());
        params.put("keyword",keyword);

        ApiClientHelper.postApi(ApiSetting.searchDistrict(), new TypeToken<ArrayList<ServiceDistrictItem>>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<ArrayList<ServiceDistrictItem>>>() {
            @Override
            public void onResponse(ApiResult<ArrayList<ServiceDistrictItem>> result) {

                if (!result.success) {
                    ToastUtil.displayLongToastMsg(SearchDistrictAreaActivity.this, result.getMsg());
                    return;
                }

                ArrayList<ServiceDistrictItem> mList = result.getResult();
                mAdapter.updateData(mList);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtil.displayShortToastMsg(SearchDistrictAreaActivity.this, volleyError.getMessage());
            }
        }, this);
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable content) {
        if (StringUtil.isNullOrEmpty(content.toString())) {
            mIv_clear.setVisibility(View.GONE);
        }else{
            mIv_clear.setVisibility(View.VISIBLE);
        }
        searchDistrict();
    }

    public class ServiceDistrictAdapter extends  RecyclerView.Adapter<SearchDistrictAreaActivity.ServiceDistrictAdapter.DistrictViewHolder>{

        public ArrayList<ServiceDistrictItem> mDataList = new ArrayList<>();

        public void updateData (ArrayList<ServiceDistrictItem> list){
            mDataList = list;
            notifyDataSetChanged();
        }

        public void clearData(){
            mDataList.clear();
            notifyDataSetChanged();
        }

        @Override
        public SearchDistrictAreaActivity.ServiceDistrictAdapter.DistrictViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View mView = LayoutInflater.from(SearchDistrictAreaActivity.this).inflate(R.layout.service_district_list_item, parent, false);
            return new SearchDistrictAreaActivity.ServiceDistrictAdapter.DistrictViewHolder(mView);
        }

        @Override
        public void onBindViewHolder(SearchDistrictAreaActivity.ServiceDistrictAdapter.DistrictViewHolder _holder, int position) {

            final ServiceDistrictItem item = mDataList.get(position);
            final SearchDistrictAreaActivity.ServiceDistrictAdapter.DistrictViewHolder holder = _holder;


            holder.mTv_district_name.setText(item.serviceName);
            StringBuilder highWayNameAndDirection = new StringBuilder(item.expressWayName);
            highWayNameAndDirection.append(" --- ").append(item.direction);
            holder.mTv_highway_name.setText(highWayNameAndDirection.toString());
            Glide.with(ExApplication.getInstance().getApplicationContext())
                    .load(item.imageUrl)
                    .asBitmap()
                    .placeholder(R.drawable.default_img)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .centerCrop()
                    .into(holder.mIv_img);

            holder.mTv_distance.setText(String.valueOf(item.distance) + getString(R.string.distance_unit));

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finishActivity(ServiceDistrictListActivity.class);
                    DistrictDetailActivity.launch(SearchDistrictAreaActivity.this,item);
                    finish();
                }
            });
        }

        @Override
        public int getItemCount() {
            return mDataList == null ? 0 :mDataList.size();
        }

        class DistrictViewHolder extends RecyclerView.ViewHolder {

            @Bind(R.id.tv_district_name) TextView mTv_district_name;
            @Bind(R.id.tv_express_way_name) TextView mTv_highway_name;
            @Bind(R.id.tv_distance) TextView mTv_distance;
            @Bind(R.id.iv_district_img)
            ImageView mIv_img;

            public DistrictViewHolder(View itemView){
                super(itemView);
                ButterKnife.bind(this,itemView);
            }

        }
    }

}
